<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>ws demo</title>
</head>

<body>
    <h3>WebSocket Go</h3>
    <pre id="output"></pre>

    <script>
        var url = 'ws://localhost:1234/ws';
        var c = new WebSocket(url);

        var outputEl = document.getElementById('output')

        // 发送消息
        var send = function (data) {
            var _el = document.createElement('p')
            _el.innerText = new Date() + " ==> " + data
            outputEl.appendChild(_el)
            c.send(data)
        }

        // 获取消息
        c.onmessage = function (msg) {
            var _el = document.createElement('p')
            _el.innerText = new Date() + " <== " + msg.data
            outputEl.appendChild(_el)
            console.log(msg)
        }

        // 打开连接
        c.onopen = function () {
            setInterval(
                function () { send("ping") }
                , 1000)
        }

        // 关闭连接
        c.onclose = function () {
            console.log('关闭了连接')
        }
    </script>
</body>

</html>